<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-input placeholder="请输入内容" v-model="searchUser" class="search-input">
      <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
    </el-input>

    <el-button type="primary" plain @click="handleAdd">添加用户</el-button>

    <!-- 表格的data属性表示表格渲染的数据 -->
    <el-table
      class="mt-15 mb-15"
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <!-- prop表示每一列渲染的数据的字段名 -->
      <el-table-column
        prop="username"
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        label="状态">
        <!-- 要往表格中插入其他的组件或者标签，需要使用作用域插槽 -->
        <template slot-scope="scope">
          <!-- 通过scope变量的row属性（row属性是组件内部封装好的），能够获取表格当前那一行的数据 -->
          <el-switch
            v-model="scope.row.mg_state"
            :disabled="scope.row.username==='admin'"
            @change="handleChange(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)"></el-button>
          <el-button type="success" icon="el-icon-check" circle @click="handleGrant(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加用户对话框  -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addFrom" :rules="myrules" ref="addRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="addFrom.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="addFrom.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addFrom.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addFrom.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="conirmAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" :rules="myrules" ref="editRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="conirmEdit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantForm" :rules="myrules">
        <el-form-item label="当前用户" label-width="120px">
          <el-input v-model="grantForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="请选择角色" label-width="120px">
          <el-select v-model="selectRoleId" placeholder="请选择">
            <!-- label属性用来指定后台返回的数据中，哪个字段用来展示汉字 -->
            <!-- value属性用来指定后台返回的数据中哪个字段用来获取点击之后的选项数据（该值需要传递给后台） -->
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="conirmGrant">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getUsers, changeUserState, addUser, editUser, deleteUser, getRoleList, grantUserRole } from '@/api'
export default {
  data () {
    // 校验函数
    let chackEmail = (rule, value, cb) => {
      if (value === '') {
        cb(new Error('邮箱不能为空'))
      } else {
        // 不为空，但是需要校验邮箱的格式
        let emailReg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}/
        if (emailReg.test(value)) {
          // 校验通过
          cb()
        } else {
          // 校验不通过
          cb(new Error('请输入正确的邮箱格式'))
        }
      }
    }
    return {
      currentPage: 1,
      searchUser: '', //  搜索框中的值
      tableData: [],
      total: 0, // 数据总条数
      pagesize: 3, // 每页多少条，默认3条
      pagenum: 1, // 当前页码，默认为第一页

      loading: false, // 表格加载动画

      addDialogFormVisible: false, // 添加用户对话框显示和隐藏
      formLabelWidth: '80px',
      // 添加用户的表单对象
      addFrom: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },

      editDialogFormVisible: false, // 编辑用户对话框显示和隐藏
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },

      grantDialogFormVisible: false, // 分配角色对话框显示和隐藏
      grantForm: {
        username: '',
        id: ''
      },
      selectRoleId: '', // 获取选择器选择的角色
      // 选择器组件的数据
      options: [],
      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          // validator属性用于自定义校验规则，后面跟一个函数
          { required: true, validator: chackEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 调用初始化表格数据方法
    this.initTable()
  },
  methods: {
    // 初始化表格数据
    initTable () {
      // 发请求之前开启加载动画
      this.loading = true
      getUsers({ query: this.searchUser, pagenum: this.pagenum, pagesize: this.pagesize })
        .then(res => {
          // 给表格数据赋值
          this.tableData = res.data.data.users
          this.total = res.data.data.total
          // 请求完成之后关闭加载动画
          this.loading = false
        })
    },
    // 搜索用户
    search () {
      // 重置请求页码为第一页
      this.pagenum = 1
      // 重置当前页码为第一页
      this.currentPage = 1
      this.initTable()
    },
    // 1.2 切换用户状态
    handleChange (row) {
      console.log(row)
      changeUserState(row.id, row.mg_state)
        .then(res => {
          if (res.data.meta.status === 200) {
            // 成功的弹框
            this.$message.success(res.data.meta.msg)
            // 刷新数据
            this.initTable()
          } else {
            this.$message.error(res.data.meta.msg)
          }
        })
    },
    // 添加用户
    handleAdd () {
      this.addDialogFormVisible = true
      // 上面的赋值操作是一个异步操作，如果直接获取ref的dom引用会报错，解决方式将获取dom的操作放在this.$nextTik()方法中
      this.$nextTick(() => {
        // 清除表单的校验结果
        this.$refs.addRef.clearValidate()
      })
    },
    // 确定提交添加用户
    conirmAdd () {
      // 提交添加用户时需要再进行js校验
      this.$refs.addRef.validate(isPass => {
        if (isPass) {
          addUser(this.addFrom)
            .then(res => {
              if (res.data.meta.status === 201) {
                this.$message.success(res.data.meta.msg)
                // 清空表单
                this.addFrom.username = ''
                this.addFrom.password = ''
                this.addFrom.email = ''
                this.addFrom.mobile = ''
                this.addDialogFormVisible = false
                this.initTable()
              } else {
                this.$message.erro(res.data.meta.msg)
              }
            })
        } else {
          this.$message.error('请填写正确的表单格式')
        }
      })
    },

    // 点击编辑按钮
    handleEdit (row) {
      this.editDialogFormVisible = true
      this.editForm.username = row.username
      this.editForm.mobile = row.mobile
      this.editForm.email = row.email
      this.editForm.id = row.id
    },

    // 确定编辑
    conirmEdit () {
      console.log('确定编辑')
      this.$refs.editRef.validate(isPass => {
        if (isPass) {
          editUser(this.editForm)
            .then(res => {
              if (res.data.meta.status === 200) {
                this.$message.success(res.data.meta.msg)
                // 清空表单
                this.editForm.username = ''
                this.editForm.id = ''
                this.editForm.email = ''
                this.editForm.mobile = ''
                this.editDialogFormVisible = false
                this.initTable()
              } else {
                this.$message.error(res.data.meta.msg)
              }
            })
        } else {
          this.$message.error('请填写正确的表单格式')
        }
      })
    },

    // 点击删除
    handleDelete (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定之后的操作
        deleteUser(row.id)
          .then(res => {
            if (res.data.meta.status === 200) {
              // 弹出提示信息
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              // 刷新列表
              this.initTable()
            } else {
              this.$message.error(res.data.meta.msg)
            }
          })
      }).catch(() => {
        // 点击取消之后的操作
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 获取选择器的角色列表
    getRoles () {
      getRoleList()
        .then(res => {
          this.options = res.data.data
        })
    },

    // 点击分配角色
    handleGrant (row) {
      this.selectRoleId = row.role_name // 解决bug
      this.grantForm.username = row.username
      this.grantForm.id = row.id
      this.getRoles()
      this.grantDialogFormVisible = true
    },
    // 确认分配角色
    conirmGrant () {
      // 在正式发送分配角色请求之前，要先判断selectRoleId是否为字符串，如果是字符串说明用户没有更改选项，就不能够让他发送这个确认请求
      if (typeof this.selectRoleId === 'string') {
        this.grantDialogFormVisible = false
        return false
      }
      grantUserRole(this.grantForm.id, this.selectRoleId)
        .then(res => {
          console.log(res)
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.grantDialogFormVisible = false
            this.initTable()
          } else {
            this.$message.error(res.data.meta.msg)
          }
        })
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      // 改变每页多少条以后重新发送请求
      this.initTable()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.pagenum = val
      this.initTable()
    }
  }
}
</script>
<style lang="scss" scoped>
.search-input {
  width: 300px;
  margin-right: 10px;
}
</style>
